import * as echarts from 'echarts'
import {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react'
import CountUp from 'react-countup'

import rank1 from '@/assets/icons/ranking/rank_1.png'
import rank2 from '@/assets/icons/ranking/rank_2.png'
import rank3 from '@/assets/icons/ranking/rank_3.png'
import arrowBorder from '@/assets/icons/safeCoGovernance/arrow_border.png'
import { priceSwitch, splicePlateNum } from '@/utils/compUtils'

import { generateCountArray } from '../../../BigScreenBase/utils'
import WordHScroll from '../../Components/WordHScroll'
import { WorkOrderRecord } from '../../data'

export interface ItemRenderRef {
  resize(): void
  clearCountUp(): void
  refreshAboutCountUp(): void
  initialData(type: 'inital' | 'switchAssociation', sum: number): void
  intervalRefresh(sum: number): void
}

interface ItemRenderProps {
  label: string
  rankList?: string[]
  style?: React.CSSProperties
  data?: WorkOrderRecord[]
}

const rankImgMap = [rank1, rank2, rank3]
const color = [
  [
    'rgba(102, 204, 170, 1)',
    'rgba(102, 204, 170, 0.32)',
    'rgba(102, 204, 170, 1)'
  ],
  [
    'rgba(255, 102, 102, 1)',
    'rgba(255, 102, 102, 0.32)',
    'rgba(245, 86, 80, 1)'
  ]
]

const ItemRender = forwardRef<ItemRenderRef, ItemRenderProps>((props, ref) => {
  const { label, rankList = [], data = [], style } = props
  const chartDom = useRef<HTMLDivElement>(null)
  const myChart = useRef<echarts.EChartsType>()

  const allWarnSumRef = useRef<number>(0)

  const [prevAllWarnSum, setPrevAllWarnSum] = useState<number>(0)
  const prevAllWarnSumRef = useRef<number>(0)
  const [endAllWarnSum, setEndAllWarnSum] = useState<number>(0)
  const endAllWarnSumRef = useRef<number>(0)

  // timeout
  const allWarnSumTimeoutIdRef = useRef<any>()

  //数据/时间 分组
  const allWarnSumUpGroupRef = useRef<{
    countGroup: number[]
    timeGroup: number[]
  }>({
    countGroup: [],
    timeGroup: []
  })

  const allWarnSumUpGroupIndexRef = useRef<number>(0)

  //数字翻牌器
  function _recursionWarnSumSetStartEndCount(gorupIndex: number) {
    if (gorupIndex > allWarnSumUpGroupRef.current.countGroup.length - 1) {
      if (allWarnSumTimeoutIdRef.current) {
        clearTimeout(allWarnSumTimeoutIdRef.current)
      }
      if (endAllWarnSumRef.current !== allWarnSumRef.current) {
        console.error(
          `endAllWarnSumRef.current 【${endAllWarnSumRef.current}】!==allWarnSumRef 【${allWarnSumRef.current}】`
        )
      }
      return
    }

    const timeoutTime = Math.max(
      1,
      allWarnSumUpGroupRef.current.timeGroup[gorupIndex] - 1
    ) //CountUp duration需要1s

    if (allWarnSumTimeoutIdRef.current) {
      clearTimeout(allWarnSumTimeoutIdRef.current)
    }
    allWarnSumTimeoutIdRef.current = setTimeout(() => {
      if (gorupIndex === 0) {
        //初始化时是从1开始的，以后每次更新是从0开始的
        prevAllWarnSumRef.current = endAllWarnSumRef.current
      } else if (gorupIndex > 0) {
        prevAllWarnSumRef.current +=
          allWarnSumUpGroupRef.current.countGroup[gorupIndex - 1]
      }
      setPrevAllWarnSum(prevAllWarnSumRef.current)

      const currEndCount =
        allWarnSumUpGroupRef.current.countGroup[gorupIndex] +
        prevAllWarnSumRef.current
      endAllWarnSumRef.current = currEndCount
      setEndAllWarnSum(currEndCount)
    }, timeoutTime * 1000)
  }

  const handleAllWrnSumCountUpEnd = () => {
    allWarnSumUpGroupIndexRef.current += 1
    _recursionWarnSumSetStartEndCount(allWarnSumUpGroupIndexRef.current)
  }

  function clearCountUp() {
    if (allWarnSumTimeoutIdRef.current) {
      clearTimeout(allWarnSumTimeoutIdRef.current)
      allWarnSumTimeoutIdRef.current = undefined
    }
  }

  function _refreshAboutCountUp() {
    clearCountUp()
    allWarnSumRef.current = 0
    setPrevAllWarnSum(0)
    prevAllWarnSumRef.current = 0
    setEndAllWarnSum(0)
    endAllWarnSumRef.current = 0
    allWarnSumUpGroupRef.current = {
      countGroup: [],
      timeGroup: []
    }
    allWarnSumUpGroupIndexRef.current = 0
  }

  useEffect(() => {
    if (!chartDom.current) {
      return
    }
    const data2 = (data ?? []).map((v: any, i: number) => {
      return {
        ...v,
        labelColor: color[i][2],
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: color[i][0] }, // 0% 处的颜色
              { offset: 1, color: color[i][1] } // 100% 处的颜色
            ],
            global: false // 缺省为 false
          }
        }
      }
    })
    if (!myChart.current) {
      // 初始化值
      myChart.current = echarts.init(chartDom.current, null, {
        renderer: 'canvas'
      })
      myChart.current.setOption({
        showEmptyCircle: true,
        //提醒条
        tooltip: {
          show: false,
          trigger: 'item'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: ['79%', '100%'],
            center: ['center', 'center'],
            // padAngle: 4,
            labelLine: {
              show: false
            },
            label: {
              show: false
            },
            itemStyle: {
              // borderRadius: 10,
              borderColor: '#181818',
              borderWidth: 2
            },
            avoidLabelOverlap: false,
            animation: true,
            hoverAnimation: true,
            emphasis: {
              scale: false
            },
            emptyCircleStyle: {
              color: 'rgba(0, 0, 0, 0.60)' // 设置没数据的样式
            }
          },

          {
            type: 'pie',
            zlevel: 2,
            silent: true,
            radius: ['50%', '52%'],
            center: ['50%', '50%'],
            startAngle: 50,
            emptyCircleStyle: {
              color: 'rgba(255, 255, 255, 0.12)'
            }
          }
        ]
      })
    } else if (myChart.current) {
      myChart.current.setOption({
        showEmptyCircle: true,
        series: [
          {
            data: data2.every((item: any) => item.value === 0) ? [] : data2,
            emptyCircleStyle: {
              color: 'rgba(0, 0, 0, 0.60)' // 设置没数据的样式
            }
          }
        ]
      })
    }
  }, [data])
  useEffect(() => {
    return () => {
      if (myChart.current && !myChart.current.isDisposed()) {
        echarts.dispose(myChart.current)
      }
    }
  }, [])

  /*视口改变 echarts  -resize*/
  useImperativeHandle(ref, () => ({
    resize: () => {
      if (myChart.current) {
        myChart.current.resize()
      }
    },
    clearCountUp,
    refreshAboutCountUp: _refreshAboutCountUp,
    initialData: (type: 'inital' | 'switchAssociation', sum: number) => {
      if (type === 'switchAssociation') {
        _refreshAboutCountUp()
      }
      allWarnSumRef.current = sum
      if (sum > 0) {
        setEndAllWarnSum(sum)
        endAllWarnSumRef.current = sum
      }
    },
    intervalRefresh: (sum: number) => {
      allWarnSumRef.current = sum
      const allWarnSumCountDiff = sum - endAllWarnSumRef.current
      if (allWarnSumCountDiff === 0) {
        return
      } else {
        allWarnSumUpGroupIndexRef.current = 0
        allWarnSumUpGroupRef.current = generateCountArray(
          endAllWarnSumRef.current,
          sum
        )
        if (allWarnSumCountDiff < 0) {
          allWarnSumUpGroupRef.current = {
            countGroup: allWarnSumUpGroupRef.current.countGroup.map(
              (count) => count * -1
            ),
            timeGroup: allWarnSumUpGroupRef.current.timeGroup
          }
        }
        _recursionWarnSumSetStartEndCount(allWarnSumUpGroupIndexRef.current)
      }
    }
  }))

  return (
    <div
      style={{
        flex: 1,
        padding: '0 24px',
        borderImage:
          'linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.24) 46%, rgba(255, 255, 255, 0) 100%) 1',
        ...style
      }}
    >
      <div
        style={{ display: 'flex', gap: 8, height: 72, alignItems: 'center' }}
      >
        <div style={{ width: '85px' }}>
          <div className="dr_count_num">
            <CountUp
              start={prevAllWarnSum}
              end={endAllWarnSum}
              duration={1}
              onEnd={handleAllWrnSumCountUpEnd}
            />
          </div>
          <div className="dr_label">{label}</div>
        </div>
        <div style={{ width: 176 }} className="warn-ranklist">
          {rankList?.length ? (
            rankList.map((item, index) => {
              const padLeft = (index + 1) * 8
              return (
                <div
                  key={item}
                  className="flexr alc"
                  style={{ gap: 2, paddingLeft: padLeft }}
                >
                  <img
                    src={rankImgMap[index]}
                    style={{ width: 16, height: 16 }}
                  />
                  <span
                    style={{
                      display: 'inline-block',
                      fontSize: 12,
                      lineHeight: '16px',
                      width: 'calc(100% - 18px)',
                      overflow: 'hidden'
                    }}
                  >
                    {label.includes('企业') ? (
                      <WordHScroll>
                        <span>{item}</span>
                      </WordHScroll>
                    ) : label.includes('车辆') ? (
                      splicePlateNum(item)
                    ) : (
                      item
                    )}
                  </span>
                </div>
              )
            })
          ) : (
            <div
              style={{
                fontSize: 12,
                color: 'rgba(255, 255, 255, 0.32)',
                paddingLeft: 24
              }}
            >
              暂无排名
            </div>
          )}
        </div>
      </div>
      <img
        src={arrowBorder}
        style={{ height: 16, width: '100%', margin: '12px 0' }}
      />
      <div className="pie-box flexr alc">
        <div
          ref={chartDom}
          style={{ width: '64px', height: '64px' }}
          className="echarts-pie"
        ></div>
        <div className="flexc" style={{ marginLeft: 27, width: 164, gap: 16 }}>
          {[...data].reverse().map((item: any, index: number) => {
            const cs = [...color].reverse()
            return (
              <div
                className="flexr jub  alc"
                key={index}
                style={{ lineHeight: '16px' }}
              >
                <div
                  className="font-family-puhuiti"
                  style={{ textAlign: 'left', marginTop: '-2px' }}
                >
                  {item.name}
                </div>

                <div
                  className="font-family-ZQKHY"
                  style={{ color: cs[index][2], width: 40 }}
                >
                  {priceSwitch(item.value) || 0}
                </div>
                <div
                  className="flexr font-family-ZQKHY"
                  style={{
                    color: 'rgba(255,255,255,0.64)',
                    flexBasis: 46,
                    justifyContent: 'flex-end'
                  }}
                >
                  {item.piont || 0}
                  <span className="bfh">%</span>
                </div>
              </div>
            )
          })}
        </div>
      </div>
    </div>
  )
})

export default ItemRender
